﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Transactions;

public partial class Main_ServiceInvoice_PurchaseOrderEdit : System.Web.UI.Page
{
    Datautility DU = new Datautility();
    string strsql = string.Empty;
    int intRowCounter = 1;
    List<string> LstRowCount;
    List<string> LstServices;
    List<string> LstTaxable;
    List<string> LstHidChildId;
    List<string> LstDescription;
    List<string> LstUnit;
    List<string> LstRate;
    List<string> LstServiceTax;
    List<string> LstPECess;
    List<string> LstHECess;
    List<string> LstTotalAmt;
    List<string> LstChkDelete;

    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);
        _OverrideAddMore();

    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userid"] == null)
        {
            Response.Redirect("~/SessionExpired.aspx");
        }
        if (!IsPostBack)
        {
            LstRowCount = new List<string>();
            ViewState["LstRowCount"] = LstRowCount;

            LstServices = new List<string>();
            ViewState["LstServices"] = LstServices;

            LstTaxable = new List<string>();
            ViewState["LstTaxable"] = LstTaxable;

            LstHidChildId = new List<string>();
            ViewState["LstHidChildId"] = LstHidChildId;

            LstDescription = new List<string>();
            ViewState["LstDescription"] = LstDescription;

            LstUnit = new List<string>();
            ViewState["LstUnit"] = LstUnit;


            LstRate = new List<string>();
            ViewState["LstRate"] = LstRate;

            LstServiceTax = new List<string>();
            ViewState["LstServiceTax"] = LstServiceTax;

            LstPECess = new List<string>();
            ViewState["LstPECess"] = LstPECess;

            LstHECess = new List<string>();
            ViewState["LstHECess"] = LstHECess;

            LstTotalAmt = new List<string>();
            ViewState["LstTotalAmt"] = LstTotalAmt;

            LstChkDelete = new List<string>();
            ViewState["LstChkDelete"] = LstChkDelete;

            _BindFormat();
            _BindCustomerLedger();
            _BindServices(ddlService1);
            txtDate.Text = string.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(System.DateTime.Now));

            _filldetails();
        }
    }

    private void _filldetails()
    {
        if (Request.QueryString != null)
        {
            string key = Request.QueryString["Poid"].ToString();
            hidPOId.Value = key.ToString();
            string pono = Request.QueryString["PONO"].ToString();
            if (pono != string.Empty)
            {
                if (pono.Contains("/"))
                {
                    string[] sd = pono.Split('/');
                    txtPrefix.Text = sd[0].ToString();
                    txtVoucher.Text = sd[1].ToString();
                    txtSuffix.Text = sd[2].ToString();
                }
            }
            string podate = Request.QueryString["PODate"].ToString();
            if (podate != string.Empty)
            {
                txtDate.Text = string.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(podate));
            }
            string client = Request.QueryString["Client"].ToString();
            if (client != string.Empty)
            {
                ddlClients.SelectedValue = ddlClients.Items.FindByText(client).Value;
            }

        }
        ddlFormat.Enabled = false;
        txtPrefix.Enabled = false;
        txtVoucher.Enabled = false;
        txtSuffix.Enabled = false;
        _fillvalue(Request.QueryString["Poid"].ToString());
    }
    private void _fillvalue(string poid)
    {
        SqlParameter[] sqlselpara =
                                   {
                                       new SqlParameter("@poid",poid)
                                   };
        DataTable dtGetDetail = DU.getdatausingprocedure("USP_IVC_SELECTPODETAILS", sqlselpara);
        if (dtGetDetail.Rows.Count > 0)
        {
            int count = dtGetDetail.Rows.Count;
            if (count == 1)
            {
                ddlService1.SelectedValue = ddlService1.Items.FindByText(dtGetDetail.Rows[0]["ServiceType"].ToString()).Value;
                txtDescription1.Text = dtGetDetail.Rows[0]["ADDDESC"].ToString();
                txtUnit1.Text = string.Format("{0:0.00}", Convert.ToDouble(dtGetDetail.Rows[0]["UNIT"].ToString()));
                txtRate1.Text = string.Format("{0:0.00}", Convert.ToDouble(dtGetDetail.Rows[0]["RATE"].ToString()));
                txtTotalAmt1.Text = string.Format("{0:0.00}", Convert.ToDouble(dtGetDetail.Rows[0]["GROSSAMT"].ToString()));


                HiddenField hidPOChildIdVal = (HiddenField)tblPODetails.Rows[1].FindControl("hidPOChildIdVal1");
                HiddenField hidChkTaxableVal = (HiddenField)tblPODetails.Rows[1].FindControl("hidChkTaxableVal1");
                HiddenField hidServiceTaxRateVals = (HiddenField)tblPODetails.Rows[1].FindControl("hidServiceTaxRateVal");
                HiddenField hidPECessRateVals = (HiddenField)tblPODetails.Rows[1].FindControl("hidPECessRateVal");
                HiddenField hidHECessRateVals = (HiddenField)tblPODetails.Rows[1].FindControl("hidHECessRateVal");
                if (dtGetDetail.Rows[0]["taxability"].ToString() == "0" && dtGetDetail.Rows[0]["subclass"].ToString() == "1")
                {
                    hidChkTaxableVal.Value = "1";
                }
                else
                {
                    hidChkTaxableVal.Value = "0";
                }
                hidPOChildIdVal.Value = dtGetDetail.Rows[0]["POCHILDID"].ToString();
                hidServiceTaxRateVals.Value = dtGetDetail.Rows[0]["SERVICETAXRATE"].ToString();
                hidPECessRateVals.Value = dtGetDetail.Rows[0]["EDUCESS1RATE"].ToString();
                hidHECessRateVals.Value = dtGetDetail.Rows[0]["EDUCESS2RATE"].ToString();
            }
            else
            {
                ddlService1.SelectedValue = ddlService1.Items.FindByText(dtGetDetail.Rows[0]["ServiceType"].ToString()).Value;
                txtDescription1.Text = dtGetDetail.Rows[0]["ADDDESC"].ToString();
                txtUnit1.Text = string.Format("{0:0.00}", Convert.ToDouble(dtGetDetail.Rows[0]["UNIT"].ToString()));
                txtRate1.Text = string.Format("{0:0.00}", Convert.ToDouble(dtGetDetail.Rows[0]["RATE"].ToString()));
                txtTotalAmt1.Text = string.Format("{0:0.00}", Convert.ToDouble(dtGetDetail.Rows[0]["GROSSAMT"].ToString()));


                HiddenField hidPOChildIdVal = (HiddenField)tblPODetails.Rows[1].FindControl("hidPOChildIdVal1");
                HiddenField hidChkTaxableVal = (HiddenField)tblPODetails.Rows[1].FindControl("hidChkTaxableVal1");
                HiddenField hidServiceTaxRateVals = (HiddenField)tblPODetails.Rows[1].FindControl("hidServiceTaxRateVal");
                HiddenField hidPECessRateVals = (HiddenField)tblPODetails.Rows[1].FindControl("hidPECessRateVal");
                HiddenField hidHECessRateVals = (HiddenField)tblPODetails.Rows[1].FindControl("hidHECessRateVal");

                if (dtGetDetail.Rows[0]["taxability"].ToString() == "0" && dtGetDetail.Rows[0]["subclass"].ToString() == "1")
                {
                    hidChkTaxableVal.Value = "1";
                }
                else
                {
                    hidChkTaxableVal.Value = "0";
                }
                hidPOChildIdVal.Value = dtGetDetail.Rows[0]["POCHILDID"].ToString();
                hidServiceTaxRateVals.Value = dtGetDetail.Rows[0]["SERVICETAXRATE"].ToString();
                hidPECessRateVals.Value = dtGetDetail.Rows[0]["EDUCESS1RATE"].ToString();
                hidHECessRateVals.Value = dtGetDetail.Rows[0]["EDUCESS2RATE"].ToString();

                int j = 2;
                for (int i = 0; i <= count - 2; i++)
                {
                    _AddMoreRow();

                    DropDownList ddlService = (DropDownList)tblPODetails.Rows[j].FindControl("ddlService" + j);
                    HiddenField hidChkTaxable = (HiddenField)tblPODetails.Rows[j].FindControl("hidChkTaxableVal" + j);
                    HiddenField hidPOChildId = (HiddenField)tblPODetails.Rows[j].FindControl("hidPOChildIdVal" + j);
                    TextBox txtDescription = (TextBox)tblPODetails.Rows[j].FindControl("txtDescription" + j);
                    TextBox txtUnit = (TextBox)tblPODetails.Rows[j].FindControl("txtUnit" + j);
                    TextBox txtRate = (TextBox)tblPODetails.Rows[j].FindControl("txtRate" + j);
                    TextBox txtTotalAmt = (TextBox)tblPODetails.Rows[j].FindControl("txtTotalAmt" + j);

                    if (dtGetDetail.Rows[i + 1]["taxability"].ToString() == "0" && dtGetDetail.Rows[i + 1]["subclass"].ToString() == "1")
                    {
                        hidChkTaxable.Value = "1";
                    }
                    else
                    {
                        hidChkTaxable.Value = "0";
                    }
                    ddlService.SelectedValue = ddlService.Items.FindByText(dtGetDetail.Rows[i + 1]["ServiceType"].ToString()).Value;
                    hidPOChildId.Value = dtGetDetail.Rows[i + 1]["POCHILDID"].ToString();
                    txtDescription.Text = dtGetDetail.Rows[i + 1]["ADDDESC"].ToString();
                    txtUnit.Text = string.Format("{0:0.00}", Convert.ToDouble(dtGetDetail.Rows[i + 1]["UNIT"].ToString()));
                    txtRate.Text = string.Format("{0:0.00}", Convert.ToDouble(dtGetDetail.Rows[i + 1]["RATE"].ToString()));
                    txtTotalAmt.Text = string.Format("{0:0.00}", Convert.ToDouble(dtGetDetail.Rows[i + 1]["GROSSAMT"].ToString()));
                    j++;
                }
            }
            DropDownList ddlprioritiesd = (DropDownList)this.FindControl("ddlpriorities");
            ddlprioritiesd.SelectedValue = ddlprioritiesd.Items.FindByText(dtGetDetail.Rows[0]["PROIRITY"].ToString()).Value;
            bool cashcredit = Convert.ToBoolean(dtGetDetail.Rows[0]["CASHCREDIT"].ToString());
            if (cashcredit == true)
            {
                rbtCashCredit.SelectedIndex = 1;
                txtCreditDay.Text = dtGetDetail.Rows[0]["CREDITDAYS"].ToString();
                txtCreditDay.Enabled = true;
            }
            else
            {
                rbtCashCredit.SelectedIndex = 0;
                txtCreditDay.Enabled = false;
            }

            DropDownList DDL = (DropDownList)this.FindControl("ddlFormat");
            DDL.SelectedValue = DDL.Items.FindByText(dtGetDetail.Rows[0]["FORMATNAME"].ToString()).Value;
            txtPreparedBy.Text = dtGetDetail.Rows[0]["PREPAREDBY"].ToString();
            txtCheckedBy.Text = dtGetDetail.Rows[0]["CHECHEDBY"].ToString();
            txtNarration.Text = dtGetDetail.Rows[0]["NARRATION"].ToString();
            txtRemarks.Text = dtGetDetail.Rows[0]["REMARKS"].ToString();
            txtTotalTaxableAmt.Text = string.Format("{0:0.00}", Convert.ToDouble(dtGetDetail.Rows[0]["TAXABLEAMT"].ToString()));
            txtTotalNonTaxableAmt.Text = string.Format("{0:0.00}", Convert.ToDouble(dtGetDetail.Rows[0]["NONTAXABLEAMT"].ToString()));
            txtTotalServiceTax.Text = string.Format("{0:0.00}", Convert.ToDouble(dtGetDetail.Rows[0]["SERVICETAXAMT"].ToString()));
            txtTotalPECess.Text = string.Format("{0:0.00}", Convert.ToDouble(dtGetDetail.Rows[0]["EDUCESS1AMT"].ToString()));
            txtTotalHECess.Text = string.Format("{0:0.00}", Convert.ToDouble(dtGetDetail.Rows[0]["EDUCESS2AMT"].ToString()));
            txtGrandTotal.Text = string.Format("{0:0.00}", Convert.ToDouble(dtGetDetail.Rows[0]["TOTALAMT"].ToString()));
            lblServiceTaxRate.Text = string.Format("{0:0.00}", Convert.ToDouble(dtGetDetail.Rows[0]["SERVICETAXRATE"].ToString())) + " %";
            lblPECessRate.Text = string.Format("{0:0.00}", Convert.ToDouble(dtGetDetail.Rows[0]["EDUCESS1RATE"].ToString())) + " %";
            lblHECessRate.Text = string.Format("{0:0.00}", Convert.ToDouble(dtGetDetail.Rows[0]["EDUCESS2RATE"].ToString())) + " %";
            txtUnit1.Focus();
        }
    }
    private void _RemoveSingleRow()
    {

        int d = Convert.ToInt32(tblPODetails.Rows.Count);
        if (d > 2)
        {
            //HiddenField hidchildid = (HiddenField)tblPODetails.Rows[d - 1].FindControl("hidPOChildIdVal" + (d - 1).ToString());
            //if (hidchildid.Value.ToString() != "0")
            //{
            //    string strsql = "delete from IVC_PURCHASEORDER_CHILD where POCHILDID='" + hidchildid.Value.ToString() + "'";
            //}
            tblPODetails.Rows.RemoveAt(d - 1);
            int count = Convert.ToInt32(hidControl.Value.ToString());
            count--;
            hidControl.Value = count.ToString();
            LstRowCount.RemoveAt(d - 3);
            LstServices.RemoveAt(d - 3);
            LstTaxable.RemoveAt(d - 3);
            LstHidChildId.RemoveAt(d - 3);
            LstDescription.RemoveAt(d - 3);
            LstUnit.RemoveAt(d - 3);
            LstRate.RemoveAt(d - 3);
            LstServiceTax.RemoveAt(d - 3);
            LstPECess.RemoveAt(d - 3);
            LstHECess.RemoveAt(d - 3);
            LstChkDelete.RemoveAt(d - 3);
            LstTotalAmt.RemoveAt(d - 3);
            ViewState["LstRowCount"] = LstRowCount;
            ViewState["LstServices"] = LstServices;
            ViewState["LstTaxable"] = LstTaxable;
            ViewState["LstHidChildId"] = LstHidChildId;
            ViewState["LstDescription"] = LstDescription;
            ViewState["LstUnit"] = LstUnit;
            ViewState["LstRate"] = LstRate;
            ViewState["LstServiceTax"] = LstServiceTax;
            ViewState["LstPECess"] = LstPECess;
            ViewState["LstHECess"] = LstHECess;
            ViewState["LstTotalAmt"] = LstTotalAmt;
            ViewState["LstChkDelete"] = LstChkDelete;

        }
        txtUnit1.Focus();

    }
    private void _BindFormat()
    {
        SqlParameter[] sapram ={
                                  new SqlParameter("@FormatId","0")
                             };
        DataTable DTFormat = DU.getdatausingprocedure("USP_IVC_GetPurchaseOrderFormat", sapram);
        ddlFormat.DataSource = DTFormat;
        ddlFormat.DataTextField = "FormatName";
        ddlFormat.DataValueField = "FormatId";
        ddlFormat.DataBind();
    }
    private void _BindCustomerLedger()
    {
        DataTable DTFormat = DU.getdatausingprocedure("USP_IVC_GetCustomerLedger");
        if (DTFormat.Rows.Count > 0)
        {
            ddlClients.DataSource = DTFormat;
            ddlClients.DataTextField = "LNAME";
            ddlClients.DataValueField = "LID";
            ddlClients.DataBind();
            ddlClients.Items.Insert(0, new ListItem("-Select Client-", "0"));
        }
    }

    private void _AddMoreRow()
    {
        intRowCounter++;
        HtmlTableRow HTRow = new HtmlTableRow();

        HtmlTableCell HTCell0 = new HtmlTableCell();
        HTCell0.Align = "center";
        CheckBox chkDelete = new CheckBox();
        chkDelete.ID = "chkDelete" + intRowCounter.ToString();
        chkDelete.Width = Unit.Percentage(98);
        chkDelete.Attributes.Add("onclick", "checkAlLChecked();");
        HTCell0.Controls.Add(chkDelete);
        LstChkDelete.Add(chkDelete.ID);

        HtmlTableCell HTCell1 = new HtmlTableCell();
        DropDownList ddlService = new DropDownList();
        ddlService.ID = "ddlService" + intRowCounter.ToString();
        ddlService.CssClass = "dropdown";
        ddlService.Width = Unit.Percentage(98);
        _BindServices(ddlService);
        ddlService.AutoPostBack = true;
        ddlService.SelectedIndexChanged += new EventHandler(ddlService_SelectedIndexChanged);
        HiddenField hidChkTaxableVal = new HiddenField();
        hidChkTaxableVal.ID = "hidChkTaxableVal" + intRowCounter.ToString();
        HiddenField hidPOChildIdVal = new HiddenField();
        hidPOChildIdVal.ID = "hidPOChildIdVal" + intRowCounter.ToString();
        hidPOChildIdVal.Value = "0";

        HTCell1.Controls.Add(ddlService);
        HTCell1.Controls.Add(hidChkTaxableVal);
        HTCell1.Controls.Add(hidPOChildIdVal);
        LstRowCount.Add(intRowCounter.ToString());
        LstServices.Add(ddlService.ID);
        LstTaxable.Add(hidChkTaxableVal.ID);
        LstHidChildId.Add(hidPOChildIdVal.ID);

        HtmlTableCell HTCell2 = new HtmlTableCell();
        TextBox txtDescription = new TextBox();
        txtDescription.ID = "txtDescription" + intRowCounter.ToString();
        txtDescription.CssClass = "input";
        txtDescription.Width = Unit.Percentage(98);
        HTCell2.Controls.Add(txtDescription);
        LstDescription.Add(txtDescription.ID);

        HtmlTableCell HTCell3 = new HtmlTableCell();
        TextBox txtUnit = new TextBox();
        txtUnit.ID = "txtUnit" + intRowCounter.ToString();
        txtUnit.CssClass = "inputnumber";
        txtUnit.Width = Unit.Percentage(98);
        txtUnit.Attributes.Add("onKeyPress", "return isNumberKey(this.id,event);");
        txtUnit.Attributes.Add("onblur", "return CalculateAmount();");
        HTCell3.Controls.Add(txtUnit);
        LstUnit.Add(txtUnit.ID);

        HtmlTableCell HTCell4 = new HtmlTableCell();
        TextBox txtRate = new TextBox();
        txtRate.ID = "txtRate" + intRowCounter.ToString();
        txtRate.CssClass = "inputnumber";
        txtRate.Width = Unit.Percentage(98);
        txtRate.Attributes.Add("onKeyPress", "return isNumberKey(this.id,event);");
        txtRate.Attributes.Add("onblur", "return CalculateAmount();");
        HiddenField hidServiceTaxAmtVal = new HiddenField();
        hidServiceTaxAmtVal.ID = "hidServiceTaxAmtVal" + intRowCounter.ToString();
        HiddenField hidPECessAmtVal = new HiddenField();
        hidPECessAmtVal.ID = "hidPECessAmtVal" + intRowCounter.ToString();
        HiddenField hidHECessAmtVal = new HiddenField();
        hidHECessAmtVal.ID = "hidHECessAmtVal" + intRowCounter.ToString();
        hidPOChildIdVal.Value = "0";
        HTCell4.Controls.Add(txtRate);
        HTCell4.Controls.Add(hidServiceTaxAmtVal);
        HTCell4.Controls.Add(hidPECessAmtVal);
        HTCell4.Controls.Add(hidHECessAmtVal);
        LstRate.Add(txtRate.ID);
        LstServiceTax.Add(hidServiceTaxAmtVal.ID);
        LstPECess.Add(hidPECessAmtVal.ID);
        LstHECess.Add(hidHECessAmtVal.ID);

        HtmlTableCell HTCell5 = new HtmlTableCell();
        TextBox txtTotalAmt = new TextBox();
        txtTotalAmt.ID = "txtTotalAmt" + intRowCounter.ToString();
        txtTotalAmt.CssClass = "DisableInputNumber";
        txtTotalAmt.Width = Unit.Percentage(98);
        txtTotalAmt.Attributes.Add("onkeydown", "return EnabledTabKey(this.id,event);");
        HTCell5.Controls.Add(txtTotalAmt);
        LstTotalAmt.Add(txtTotalAmt.ID);

        HTRow.Cells.Add(HTCell0);
        HTRow.Cells.Add(HTCell1);
        HTRow.Cells.Add(HTCell2);
        HTRow.Cells.Add(HTCell3);
        HTRow.Cells.Add(HTCell4);
        HTRow.Cells.Add(HTCell5);
        tblPODetails.Rows.Add(HTRow);

        hidControl.Value = intRowCounter.ToString();


        ViewState["LstRowCount"] = LstRowCount;
        ViewState["LstServices"] = LstServices;
        ViewState["LstTaxable"] = LstTaxable;
        ViewState["LstHidChildId"] = LstHidChildId;
        ViewState["LstDescription"] = LstDescription;
        ViewState["LstUnit"] = LstUnit;
        ViewState["LstRate"] = LstRate;
        ViewState["LstServiceTax"] = LstServiceTax;
        ViewState["LstPECess"] = LstPECess;
        ViewState["LstHECess"] = LstHECess;
        ViewState["LstTotalAmt"] = LstTotalAmt;
        ViewState["LstChkDelete"] = LstChkDelete;

    }
    private void _OverrideAddMore()
    {
        LstRowCount = (List<string>)ViewState["LstRowCount"];
        LstServices = (List<string>)ViewState["LstServices"];
        LstTaxable = (List<string>)ViewState["LstTaxable"];
        LstHidChildId = (List<string>)ViewState["LstHidChildId"];
        LstDescription = (List<string>)ViewState["LstDescription"];
        LstUnit = (List<string>)ViewState["LstUnit"];
        LstRate = (List<string>)ViewState["LstRate"];
        LstServiceTax = (List<string>)ViewState["LstServiceTax"];
        LstPECess = (List<string>)ViewState["LstPECess"];
        LstHECess = (List<string>)ViewState["LstHECess"];
        LstTotalAmt = (List<string>)ViewState["LstTotalAmt"];
        LstChkDelete = (List<string>)ViewState["LstChkDelete"];
        if (LstRowCount != null)
        {
            int Count = Convert.ToInt32(LstRowCount.Count);
            for (int i = 0; i < Count; i++)
            {
                intRowCounter++;
                HtmlTableRow HTRow = new HtmlTableRow();

                HtmlTableCell HTCell0 = new HtmlTableCell();
                HTCell0.Align = "Center";

                CheckBox chkDelete = new CheckBox();
                chkDelete.ID = LstChkDelete[i].ToString();
                chkDelete.Width = Unit.Percentage(98);
                chkDelete.Attributes.Add("onclick", "checkAlLChecked();");
                HTCell0.Controls.Add(chkDelete);

                HtmlTableCell HTCell1 = new HtmlTableCell();
                DropDownList ddlService = new DropDownList();
                ddlService.ID = LstServices[i].ToString();
                ddlService.CssClass = "dropdown";
                ddlService.Width = Unit.Percentage(98);
                _BindServices(ddlService);
                ddlService.AutoPostBack = true;
                ddlService.SelectedIndexChanged += new EventHandler(ddlService_SelectedIndexChanged);
                HiddenField hidChkTaxableVal = new HiddenField();
                hidChkTaxableVal.ID = LstTaxable[i].ToString();
                HiddenField hidPOChildIdVal = new HiddenField();
                hidPOChildIdVal.ID = LstHidChildId[i].ToString();
                hidPOChildIdVal.Value = "0";
                HTCell1.Controls.Add(ddlService);
                HTCell1.Controls.Add(hidChkTaxableVal);
                HTCell1.Controls.Add(hidPOChildIdVal);

                HtmlTableCell HTCell2 = new HtmlTableCell();
                TextBox txtDescription = new TextBox();
                txtDescription.ID = LstDescription[i].ToString();
                txtDescription.CssClass = "input";
                txtDescription.Width = Unit.Percentage(98);
                HTCell2.Controls.Add(txtDescription);


                HtmlTableCell HTCell3 = new HtmlTableCell();
                TextBox txtUnit = new TextBox();
                txtUnit.ID = LstUnit[i].ToString();
                txtUnit.CssClass = "inputnumber";
                txtUnit.Width = Unit.Percentage(98);
                txtUnit.Attributes.Add("onKeyPress", "return isNumberKey(this.id,event);");
                txtUnit.Attributes.Add("onblur", "return CalculateAmount();");
                HTCell3.Controls.Add(txtUnit);


                HtmlTableCell HTCell4 = new HtmlTableCell();
                TextBox txtRate = new TextBox();
                txtRate.ID = LstRate[i].ToString();
                txtRate.CssClass = "inputnumber";
                txtRate.Width = Unit.Percentage(98);
                txtRate.Attributes.Add("onKeyPress", "return isNumberKey(this.id,event);");
                txtRate.Attributes.Add("onblur", "return CalculateAmount();");
                HiddenField hidServiceTaxAmtVal = new HiddenField();
                hidServiceTaxAmtVal.ID = LstServiceTax[i].ToString();
                HiddenField hidPECessAmtVal = new HiddenField();
                hidPECessAmtVal.ID = LstPECess[i].ToString();
                HiddenField hidHECessAmtVal = new HiddenField();
                hidHECessAmtVal.ID = LstHECess[i].ToString();
                HTCell4.Controls.Add(txtRate);
                HTCell4.Controls.Add(hidServiceTaxAmtVal);
                HTCell4.Controls.Add(hidPECessAmtVal);
                HTCell4.Controls.Add(hidHECessAmtVal);

                HtmlTableCell HTCell5 = new HtmlTableCell();
                TextBox txtTotalAmt = new TextBox();
                txtTotalAmt.ID = LstTotalAmt[i].ToString();
                txtTotalAmt.CssClass = "DisableInputNumber";
                txtTotalAmt.Width = Unit.Percentage(98);
                txtTotalAmt.Attributes.Add("onkeydown", "return EnabledTabKey(this.id,event);");
                HTCell5.Controls.Add(txtTotalAmt);

                HTRow.Cells.Add(HTCell0);
                HTRow.Cells.Add(HTCell1);
                HTRow.Cells.Add(HTCell2);
                HTRow.Cells.Add(HTCell3);
                HTRow.Cells.Add(HTCell4);
                HTRow.Cells.Add(HTCell5);
                tblPODetails.Rows.Add(HTRow);

            }

        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            using (TransactionScope scope = new TransactionScope())
            {
                _SavePurchaseOrder_Main(hidPOId.Value);
                scope.Complete();
            }
            Response.Redirect("PurchaseOrderView.aspx");
        }
        catch (Exception ex)
        {
            lblMsg.Text = ex.Message;
        }
    }
    protected void ddlFormat_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void btnAddMore_Click(object sender, EventArgs e)
    {
        _AddMoreRow();
    }
    private void _BindServices(DropDownList ddl)
    {
        DataTable DT = DU.getdatausingprocedure("USP_IVC_GetAllServices");
        ddl.DataSource = DT;
        ddl.DataTextField = "SERVICENAME";
        ddl.DataValueField = "SERVICEID";
        ddl.DataBind();
        ddl.Items.Insert(0, new ListItem("-Select-", "0"));
    }

    protected void ddlService_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList ddl = (DropDownList)sender;
        if (ddl.SelectedValue != "0")
        {
            string ddlid = ddl.ID.ToString().Substring(10);
            int rowIndex = Convert.ToInt32(ddlid.ToString());
            strsql = "select taxability,subclass from IVC_SERVICEMASTER where serviceid='" + ddl.SelectedValue + "'";
            DataTable DTTax = DU.getdata(strsql);
            HiddenField hidChkTaxableVal = (HiddenField)tblPODetails.Rows[rowIndex].FindControl("hidChkTaxableVal" + rowIndex.ToString());
            if (DTTax.Rows.Count > 0)
            {
                if (DTTax.Rows[0]["taxability"].ToString() == "0" && DTTax.Rows[0]["subclass"].ToString() == "1")
                {
                    hidChkTaxableVal.Value = "1";
                }
                else
                {
                    hidChkTaxableVal.Value = "0";
                }
            }
        }
    }
    private void _GetServicePEHETax(string strCurrentDate)
    {
        if (strCurrentDate != string.Empty)
        {
            string[] str = strCurrentDate.ToString().Split('/');
            strCurrentDate = str[1] + "/" + str[0] + "/" + str[2];
            SqlParameter[] gettaxrate = 
                                        {
                                            new SqlParameter("@CURRENTDATE",strCurrentDate)
                                        };
            DataTable dtFillTaxes = DU.getdatausingprocedure("USP_IVC_GetCurrentServiceTaxRate", gettaxrate);
            if (dtFillTaxes.Rows.Count > 0)
            {
                lblServiceTaxRate.Text = string.Format("{0:0.00}", Convert.ToDouble(dtFillTaxes.Rows[0]["SERVICETAX"].ToString())) + " %";
                lblPECessRate.Text = string.Format("{0:0.00}", Convert.ToDouble(dtFillTaxes.Rows[0]["PCess"].ToString())) + " %";
                lblHECessRate.Text = string.Format("{0:0.00}", Convert.ToDouble(dtFillTaxes.Rows[0]["HCess"].ToString())) + " %";

                hidServiceTaxRateVal.Value = string.Format("{0:0.00}", Convert.ToDouble(dtFillTaxes.Rows[0]["SERVICETAX"].ToString()));
                hidPECessRateVal.Value = string.Format("{0:0.00}", Convert.ToDouble(dtFillTaxes.Rows[0]["PCess"].ToString()));
                hidHECessRateVal.Value = string.Format("{0:0.00}", Convert.ToDouble(dtFillTaxes.Rows[0]["HCess"].ToString()));
            }
        }
    }
    protected void txtDate_TextChanged(object sender, EventArgs e)
    {
        _GetServicePEHETax(txtDate.Text);
    }
    private void _SavePurchaseOrder_Main(string strPOId)
    {
        try
        {
            if (strPOId != string.Empty)
            {
                string strPoDate = string.Empty;
                if (txtDate.Text != string.Empty)
                {
                    string[] str = txtDate.Text.Split('/');
                    strPoDate = str[1] + "/" + str[0] + "/" + str[2];
                }
                if (txtCreditDay.Text == string.Empty)
                {
                    txtCreditDay.Text = "0";
                }
                if (ddlClients.SelectedValue != "0")
                {
                    SqlParameter[] sparam ={
                                       new SqlParameter("@POID",strPOId),
                                       new SqlParameter("@FORMATID",ddlFormat.SelectedValue),
                                       new SqlParameter("@PONUMBER",txtVoucher.Text.Trim()),
                                       new SqlParameter("@LID",ddlClients.SelectedValue),
                                       new SqlParameter("@PODATE",strPoDate),
                                       new SqlParameter("@FINYEAR",Session["FINYEAR"].ToString()),
                                       new SqlParameter("@PROIRITY",ddlpriorities.SelectedItem.Text),
                                       new SqlParameter("@CASHCREDIT",rbtCashCredit.SelectedValue),
                                       new SqlParameter("@CREDITDAYS",txtCreditDay.Text),
                                       new SqlParameter("@PREPAREDBY",txtPreparedBy.Text.Trim()),
                                       new SqlParameter("@CHECHEDBY",txtCheckedBy.Text.Trim()),
                                       new SqlParameter("@NARRATION",txtNarration.Text.Trim()),
                                       new SqlParameter("@REMARKS",txtRemarks.Text.Trim()),
                                       new SqlParameter("@CNAME",Session["username"].ToString())
                                   };
                    string POId = DU.ExecuteProcedure_Scope_Identity("USP_IVC_SavePurchaseOrder_Main", sparam);
                    if (Convert.ToDouble(POId) > 0)
                    {
                        _SavePurchaseOrder_Child(POId);
                        _SavePurchaseOrder_Total(POId);
                        lblMsg.Text = "Inserted Successfully...";
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    private void _SavePurchaseOrder_Child(string strPOId)
    {
        try
        {
            if (strPOId != string.Empty)
            {
                int Count = Convert.ToInt32(hidControl.Value);
                for (int i = 1; i <= Count; i++)
                {
                    CheckBox chkDelete = (CheckBox)tblPODetails.Rows[i].FindControl("chkDelete" + i.ToString());
                    DropDownList ddlService = (DropDownList)tblPODetails.Rows[i].FindControl("ddlService" + i);
                    HiddenField hidPOChildIdVal = (HiddenField)tblPODetails.Rows[i].FindControl("hidPOChildIdVal" + i);
                    HiddenField hidChkTaxableVal = (HiddenField)tblPODetails.Rows[i].FindControl("hidChkTaxableVal" + i);
                    HiddenField hidServiceTaxAmtVal = (HiddenField)tblPODetails.Rows[i].FindControl("hidServiceTaxAmtVal" + i);
                    HiddenField hidPECessAmtVal = (HiddenField)tblPODetails.Rows[i].FindControl("hidPECessAmtVal" + i);
                    HiddenField hidHECessAmtVal = (HiddenField)tblPODetails.Rows[i].FindControl("hidHECessAmtVal" + i);
                    TextBox txtDescription = (TextBox)tblPODetails.Rows[i].FindControl("txtDescription" + i);
                    TextBox txtUnit = (TextBox)tblPODetails.Rows[i].FindControl("txtUnit" + i);
                    TextBox txtRate = (TextBox)tblPODetails.Rows[i].FindControl("txtRate" + i);
                    TextBox txtTotalAmt = (TextBox)tblPODetails.Rows[i].FindControl("txtTotalAmt" + i);
                    if (ddlService.SelectedValue != "0" && txtTotalAmt.Text != string.Empty && Convert.ToDouble(txtTotalAmt.Text) > 0)
                    {
                        if (chkDelete.Checked)
                        {
                            if (hidPOChildIdVal.Value.ToString() != "0")
                            {
                                string sqlst = "delete from IVC_PURCHASEORDER_CHILD where POCHILDID='" + hidPOChildIdVal.Value.ToString() + "'";
                                DU.executesql(sqlst);
                            }
                        }
                        else
                        {
                            double dblTotalAmt = Convert.ToDouble(txtTotalAmt.Text.Trim()) + Convert.ToDouble(hidServiceTaxAmtVal.Value) + Convert.ToDouble(hidPECessAmtVal.Value) + Convert.ToDouble(hidHECessAmtVal.Value);
                            SqlParameter[] sparam ={
                                                   new SqlParameter("@POCHILDID",hidPOChildIdVal.Value),
                                                   new SqlParameter("@POID",strPOId),
                                                   new SqlParameter("@SERVICEID",ddlService.SelectedValue),
                                                   new SqlParameter("@ADDDESC",txtDescription.Text.Trim()),
                                                   new SqlParameter("@UNIT",txtUnit.Text.Trim()),
                                                   new SqlParameter("@RATE",txtRate.Text.Trim()),
                                                   new SqlParameter("@GROSSAMT",txtTotalAmt.Text.Trim()),
                                                   new SqlParameter("@SERVICETAXAMT",hidServiceTaxAmtVal.Value),
                                                   new SqlParameter("@CESS1AMT",hidPECessAmtVal.Value),
                                                   new SqlParameter("@CESS2AMT",hidHECessAmtVal.Value),
                                                   new SqlParameter("@TOTALAMT",dblTotalAmt)
                                               };
                            int result = DU.executeprocedure("USP_IVC_SavePurchaseOrder_Child", sparam);
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    private void _SavePurchaseOrder_Total(string strPOId)
    {
        try
        {
            if (strPOId != string.Empty)
            {
                double dblTotalAmtBeforeTax = Convert.ToDouble(txtTotalTaxableAmt.Text.Trim()) + Convert.ToDouble(txtTotalNonTaxableAmt.Text.Trim());
                SqlParameter[] sparam ={
                                       new SqlParameter("@POID",strPOId),
                                       new SqlParameter("@TAXABLEAMT",txtTotalTaxableAmt.Text.Trim()),
                                       new SqlParameter("@NONTAXABLEAMT",txtTotalNonTaxableAmt.Text.Trim()),
                                       new SqlParameter("@TOTALAMTBEFTAX",dblTotalAmtBeforeTax),
                                       new SqlParameter("@SERVICETAXRATE",hidServiceTaxRateVal.Value),
                                       new SqlParameter("@SERVICETAXAMT",txtTotalServiceTax.Text.Trim()),
                                       new SqlParameter("@EDUCESS1RATE",hidPECessRateVal.Value),
                                       new SqlParameter("@EDUCESS1AMT",txtTotalPECess.Text.Trim()),
                                       new SqlParameter("@EDUCESS2RATE",hidHECessRateVal.Value),
                                       new SqlParameter("@EDUCESS2AMT",txtTotalHECess.Text.Trim()),
                                       new SqlParameter("@TOTALAMT",txtGrandTotal.Text.Trim())
                                   };
                int result = DU.executeprocedure("USP_IVC_SavePurchaseOrder_Total", sparam);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("PurchaseOrderView.aspx");
    }


}
